﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ProjetoComperio.BusinessLogicLayer;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.Framework.Configuration;
using ProjetoComperio.Framework.Web.Mail;
using ProjetoComperio.Framework.Web.Security.HtmlMessages;

namespace ProjetoComperio.Presentation.Web
{
    internal class EmailProcessorWorker
    {
        public void DoWork()
        {
            while (true)
            {
                HtmlMessage htmlMessage = BuildContributionNewsMessage(new ContributionBLL().RetrieveLast24hoursRegisteredContributions());
                foreach (var person in new PersonBLL().RetrievePeopleWhoWantToReceiveComperioNews())
                    MailSender.SendMail(person.Email, "Novas contribuições cadastradas", htmlMessage.GetContent());

                Thread.Sleep(TimeSpan.FromHours(24));
            }
        }

        private HtmlMessage BuildContributionNewsMessage(List<Contribution> newContributions)
        {
            StringBuilder htmlNews = new StringBuilder();
            htmlNews.AppendLine("<table>");
            htmlNews.AppendLine("<tr>");
            htmlNews.AppendLine("<td>").AppendLine("Titulo").AppendLine("</td>");
            htmlNews.AppendLine("<td>").AppendLine("Data Registro").AppendLine("</td>");
            htmlNews.AppendLine("<td>").AppendLine("Link Visualizar").AppendLine("</td>");
            htmlNews.AppendLine("</tr>");
            var htmlMessage = HtmlMessageUtility.GetHtmlMessage(HtmlMessageUtility.Messages.CONTRIBUTIONNEWS, this.GetType());
            foreach (var newContribution in newContributions)
            {
                htmlNews.AppendLine("<tr>");
                htmlNews.AppendLine("<td>").AppendLine(newContribution.Title).AppendLine("</td");
                htmlNews.AppendLine("<td>").AppendLine(newContribution.RegisterDate.ToShortDateString()).AppendLine("</td");
                htmlNews.AppendLine("<td>");
                htmlNews.AppendLine("<a href='").Append(ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.COMPERIOURL)).Append("' a>").Append("Visualizar").Append("</a>");
                htmlNews.AppendLine("</td");
                htmlNews.AppendLine("</tr>");
            }
            htmlNews.AppendLine("</table>");
            htmlMessage.InsertContent("DATE", DateTime.Now.ToShortDateString());
            htmlMessage.InsertContent("CONTENT", htmlNews.ToString());
            return htmlMessage;
        }
    }
}